<?php

class C_challenge extends CI_Controller 
{
	public function __construct()
	{
		parent::__construct();
		
		//Checking that the user is authorized to access the page.
		user_authorization();
	}
	
	public function index()
	{
		//Loading libraries
		$this->load->library('table');
		
		//Getting the current user id.
		$user_id = $this->session->userdata('user_userid');
		
		//Creating a challenge object.
		$this->load->model('m_challenge', 'challenge');
		
		//Get information about all challenges created by the user.
		$challenges = $this->challenge->get_challenge_list($user_id);
		
		if (!empty($challenges))
		{
			//Create an array for table data.
			$table_data = array(array('Challenge Name', 'Abstract', 'Status', 'Roll', 'Delete', 'Change participants'));
			
			//Put all challenge information into the table array.
			foreach ($challenges as $c) {
					//Putting in information about how the user's connection to the challenge and, in case of owner, links to edit the challenge.
					if ($c['connection'] == 1) {
						$c['connection']		= 'Owner';
						$c['delete']			= anchor('c_challenge/delete/' . $c['id'], 'Delete');
						$c['add_participants']	= anchor('c_challenge/participants/' . $c['id'], 'Change participants');
					}
					else {
						$c['connection'] = 'Participant';
						$c['delete']			= '';
						$c['add_participants']	= '';
					}
					
					$c['status'] = $this->challenge->convert_status($c['status']);
					
					//Removing the id element from the array so it don't show up in the table.
					unset($c['id']);
					
					//Adding the challenge information to the table.
					$table_data[] = $c;
			}
			
			//Setting alternative table template.
			$table_template = array(	'row_alt_start'	=> '<tr class="alt_tr">',
										);
			$this->table->set_template($table_template); 
			
			//Generating table of challenges.
			$page_data['challenge_table'] = $this->table->generate($table_data); 
		}
		else {
			$page_data['challenge_table'] = '<p class="error">You don\'t participate in any challenges.</p>';
		}
		
		//Loading page views.
		$this->load->view('templates/v_header');
		$this->load->view('templates/v_menu_logedin');
		$this->load->view('pages/v_challenge', $page_data);
		$this->load->view('templates/v_footer');
	}
		
	public function participants($challenge_id) {
		
		//Getting the current user id.
		$user_id = $this->session->userdata('user_userid');
		
		//Creating a challenge object.
		$this->load->model('m_challenge', 'challenge');
		
		//Loading the challenge.
		$this->challenge->load_challengedata($challenge_id);
		
		//Fetching the owner id of the challenge.
		$owner_id = $this->challenge->get_info(array('owner_id'));
		
		//Loading header and menu view.
		$this->load->view('templates/v_header');
		$this->load->view('templates/v_menu_logedin');
		
		//Checking that the user is the owner of the challenge and therefore is authorized to edit participation.
		if ($user_id == $owner_id) {
			//Loading libraries.
			$this->load->helper('form');
			$this->load->library('table');
			
			//Fetching all users that are participating in the challenge.
			$participants = $this->challenge->get_participants_list();
			
			//Storing if any changes was made.
			$changes_made = FALSE;
			
			//Setting a result message for submitted changes.
			$page_data['submit_result'] = '';
			
			//If changes are submitted then do changes.
			if ($this->input->post('submit_changes')) {
				//Go thru all users to see if their participation has changed.
				foreach ($participants as $p) {
					//If the original participation was false and the new participation is not false then the user should be added.
					if ($p['participation'] == FALSE && $this->input->post('add_user_' . $p['user_id']) != FALSE) {
						//Add the participant. Default values for invitation_status, participation_status and invitation_date.
						$success = $this->challenge->add_participant(array('user_id' => $p['user_id']));
						
						if ($success) {
							//Stores that changes was made.
							$changes_made = TRUE;
						}
					}
					
					//If the original participation was not false and the new participation is false then the user should be removed.
					if ($p['participation'] != FALSE && $this->input->post('add_user_' . $p['user_id']) == FALSE) {
						//Remove the participant.
						$success = $this->challenge->update_participant(array(	'user_id'				=> $p['user_id'],
																				'participation_status'	=> 2 //2 means deleted.
																				));
						
						if ($success) {
							//Stores that changes was made.
							$changes_made = TRUE;
						}
					}
				}
				
				//If there was any changes then the participation list needs to be updated.
				if ($changes_made) {
					//Fetching all users that are participating in the challenge, again.
					$participants = $this->challenge->get_participants_list();
					
					//Changing the result message to a confirmation of changes.
					$page_data['submit_result'] = '<p class="confirmation">Your changes was successfully performed.</p>';
				}
				else {
					//Changing the result message to a error message.
					$page_data['submit_result'] = '<p class="error">No changes was done.</p>';
				}
			}
			
			//Create an array for table data.
			$table_data = array(array('Username', 'E-mail', 'Added'));
			
			//Fetching the owner id for the challenge.
			$owner_id = $this->challenge->get_info(array('owner_id'));
			
			//Put all user information into the table array.
			foreach ($participants as $p) {
				//Creating a user object.
				$this->load->model('m_user', 'user');
				$this->user->load_userdata($p['user_id']);
				
				//Fetching information about the user.
				$user_info = $this->user->get_info(array('username', 'email',));
				
				//Checking if the user is the owner. If so, don't put out any checkbox.
				if ($p['user_id'] != $owner_id) {
					//Adding an "user-added-checkbox" to the user array.
					$user_info['checkbox'] = form_checkbox('add_user_' . $p['user_id'], 'added', $p['participation']);
				}
				else {
					$user_info['checkbox'] = 'Owner';
				}
				
				//Adding the user information to the table.
				$table_data[] = $user_info;
			}
			
			//Generating table of users.
			$page_data['user_table'] = $this->table->generate($table_data);
			
			//Sending the challenge id to the view for use in the form open link.
			$page_data['challenge_id'] = $challenge_id;
			
			//Load view for editing participants.
			$this->load->view('pages/v_challenge_participants', $page_data);
		}
		else {
			//Loading view for not having access to the edit participants view.
			$this->load->view('pages/v_challenge_participants_unauthorized');
		}
		
		//Loading footer view.
		$this->load->view('templates/v_footer');
	}
	
	public function create_challenge()
	{
		//Loading functions for form handling.
		$this->load->helper('form');
		$this->load->library('form_validation');	
		
		//Setting the delimiters for error messages so they can be styled by CSS.
		$this->form_validation->set_error_delimiters('<p class="error">', '</p>');
		
		//Setting the form validation rules.
		$this->form_validation->set_rules('vName', 'Name', 'required');
		$this->form_validation->set_rules('vAbstract', 'Abstract', 'required');
		$this->form_validation->set_rules('vDescription', 'Description', 'required');		
		
		//Resetting login error message.
		$view_data['create_error'] = '';
		
		//Validating data input.											
		if ($this->form_validation->run())
		{
			//Creating a challenge object.
			$this->load->model('m_challenge', 'challenge');
			
			//Getting challenge information
			$cName = $this->input->post('vName'); 
			$cAbstract = $this->input->post('vAbstract');
			$cDescription = $this->input->post('vDescription');
			
			//TODO: NEED TO VALIDATE INPUT!!!
			if ($this->challenge->challenge_exists($cName))
			{	
				//Setting error messages for duplicating challenge's name.
				$view_data['create_error'] = '<p class="error">A challenge with this name already exists, please use a different name.</p>';
			}			
			else
			{			
				/******************************* DUPLICATE CODE ****************************************/
				//get username from the session
				$cUserID = $this->session->userdata('user_userid');
				
				//Get user object
				$this->load->model('m_user', 'user');
				
				//Loading userdata into the user object.
				$this->user->load_userdata($cUserID);		
				
				//Getting username and signup date.
				$cUserInfo = $this->user->get_info(array('username', 'signup_date'));
				
				//Trying to create challenge.
				if ($this->challenge->create(array('cName' => $cName, 'cAbstract' => $cAbstract, 'cDescription' => $cDescription, 'cUserID' => $cUserID))) 
				{
					//redirect('c_start'); 
				}
				else 
				{
					//Setting error messages for incorrect challenge information.
					$view_data['create_error'] = '<p class="error">Challenge information is not valid.</p>';	
				}
			}
		}		
		
		//keep inserted value
		$view_data['name'] = set_value('vName');		
		$view_data['description'] = set_value('vDescription');
		$view_data['abstract'] = set_value('vAbstract');
		
		//reload the create challenge page.
		$this->load->view('pages/v_challenge_create', $view_data);
		
		//Loading footer.
		$this->load->view('templates/v_footer');
	}
	
	public function delete_challenge() 
	{
		//Loading libraries
		$this->load->helper('form');
		$this->load->library('table');
		
		//Loading page header and menu.
		$this->load->view('templates/v_header');
		
		//get user id from the session
		$cUserID = $this->session->userdata('user_userid');
				
		//Creating a challenge object.
		$this->load->model('m_challenge', 'challenge');
		
		//Get information about all challenges created by the user.
		$challenges = $this->challenge->get_challenge_list($cUserID);
		
		//Create an array for table data.
		$table_data = array(array('Challenge Name', 'Abstract', 'Status'));
		
		//Put all challenge information into the table array.
		foreach ($challenges as $challenge) {
				//Adding an "add-challenge-checkbox" to the challenge array.
				$challenge['checkbox'] = form_checkbox($challenge['name'], 'add', FALSE);
				
				//Adding the challenge information to the table.
				$table_data[] = $challenge;
		}
			
		//Generating table of challenges.
		$page_data['challenge_table'] = $this->table->generate($table_data); 
		
		//Loading actual page and page footer.
		$this->load->view('pages/v_challenge_delete', $page_data);
		$this->load->view('templates/v_footer');
	}
}
?>
